#!/usr/bin/env python
#coding:utf8

from getpass import getpass
import hashlib

'''
作业: 写一个密码验证程序,正确的密码在文本里,需要你去比对,输入的密码允许错误3次,超过3次报错.
      注意编码风格以及合理使用异常.
普通版
'''

DB_PATH = 'userdb'

def open_binary(fname, mode='rb'):
    '以二进制的方式打开文件'
    return open(fname, mode)

def md5_encrypt(field):
    '字段加密函数'
    try:
        return hashlib.md5(field).hexdigest()
    except TypeError as e:
        raise e

def get_userdb(db_path=DB_PATH):
    '返回一个包含用户名和经过md5加密的密码的字典'
    user_dict = {}
    with open_binary(db_path) as fd:
        for line in fd:
            user, passwd = line.split(':')
            user_dict[user] = passwd.strip()
    return user_dict

if __name__ == '__main__':

    err_count = 0
    userdb = get_userdb()

    while err_count < 3:

        u = raw_input('Please enter your username: ')
        p = getpass('Please enter your password: ')

        if u in userdb.iterkeys():
            p = md5_encrypt(p)
            if p == userdb.get(u):
                print(
                    '\033[32mLogin Sucess, {u}.\033[0m'.format(u=u)
                )
                break
            else:
                print(
                    '\033[31mError: username or password error!\033[0m'
                )
        else:
            print(
                '\033[31mError: username or password error!\033[0m'
            )
        err_count += 1